package fr.iut2.tc1.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Upload extends FormPanel  implements ClickHandler, FormHandler
{
	
	private VerticalPanel page;
	private FileUpload champUpload;
	private Button submit;

	public Upload()
	{
		page = new VerticalPanel();
		page.setHeight("70px");
		
	    this.setAction(GWT.getModuleBaseURL()+"UploadFileServlet");

	    // Because we're going to add a FileUpload widget, we'll need to set the
	    // form to use the POST method, and multipart MIME encoding.
	    this.setEncoding(FormPanel.ENCODING_MULTIPART);
	    this.setWidget(page);
	    this.addFormHandler(this);
	    this.setMethod(METHOD_POST);
	    
		
		champUpload = new FileUpload();
		champUpload.setName("uploadFormElement");
		page.add(champUpload);
		
		submit = new Button("Envoyer l'image");
		submit.addClickHandler(this);
		page.add(submit);
	}

	@Override
	public void onClick(ClickEvent event) 
	{
		if(event.getSource()==this.submit)
		{
			if(this.champUpload.getFilename().endsWith(".jpg")||this.champUpload.getFilename().endsWith(".JPG")||this.champUpload.getFilename().endsWith(".png")||this.champUpload.getFilename().endsWith(".PNG")||this.champUpload.getFilename().endsWith(".gif")||this.champUpload.getFilename().endsWith(".GIF"))
			{
				this.submit();
			}
			else
			{
				Window.alert("Le fichier doit être de type : jpg,png ou gif");
			}
		}
		
	}

	@Override
	public void onSubmit(FormSubmitEvent event) 
	{
		
	}

	@Override
	public void onSubmitComplete(FormSubmitCompleteEvent event)
	{
		Window.alert(event.getResults());
		Window.Location.reload();
	}
	
}
